//
//  YCVCsPushTransition.m
//  DemoTransition
//
//  Created by yunsheng on 15/7/22.
//  Copyright (c) 2015年 yunsheng. All rights reserved.
//

#import "YCVCsPushTransition.h"

#import "YCPushPopViewController.h"
#import "YCPushPopDetailViewController.h"

@implementation YCVCsPushTransition

-(NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.5;
}

-(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    // 1. get the source viewcontroller and destination viewcontroller
    YCPushPopViewController *fromVC = (YCPushPopViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    YCPushPopDetailViewController *toVC = (YCPushPopDetailViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    // 2. create the snapshot of the imageview in a cell, then hide the imageview, which makes users have the thought that the imageview is moving
    UIView *snapshotView = [fromVC.selectedCell.imageView snapshotViewAfterScreenUpdates:false];
    snapshotView.frame = [containerView convertRect:fromVC.selectedCell.imageView.frame fromView:fromVC.selectedCell];
    fromVC.selectedCell.imageView.hidden = NO;
    // 3. set the destination viewcontroller's position, and set its alpha 0 which will slowly become 1 in next animation
    toVC.view.frame = [transitionContext finalFrameForViewController:toVC];
    toVC.view.alpha = 0;
    // 4. add toVC.view and snapshotView in containerView。Note that the order is correct
    [containerView addSubview:toVC.view];
    [containerView addSubview:snapshotView];
    // 5. apply the animation
    [toVC.imgView layoutIfNeeded];
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        snapshotView.frame = toVC.imgView.frame;
        toVC.view.alpha = 1;
    } completion:^(BOOL finished) {
        fromVC.selectedCell.imageView.hidden = NO;
        toVC.imgView.image = toVC.image;
        [snapshotView removeFromSuperview];
        // must remember to applay this method, and make the system manage navigation
        [transitionContext completeTransition:YES];
        
    } ];
}

@end
